Source Code Viewer - Example 9 - DOBRangeValidator

package name.matthewgreet.example9.util;

import java.util.Date;

import name.matthewgreet.strutscommons.annotation.Required.MessageType;
import name.matthewgreet.strutscommons.policy.AbstractCustomPostConversionValidatorSupport;
import name.matthewgreet.strutscommons.policy.ValidationResult;

/**
 * Custom post conversion validator that checks if a date of birth is in a sane range.
 * 
 * <DL>
 *   <DT>param1</DT><DD>Minimum age in years</DD>
 *   <DT>param2</DT><DD>Maximum age in years</DD>
 * </DL>
 */
public class DOBRangeValidator extends AbstractCustomPostConversionValidatorSupport<Date> {
    @Override
    public Class<Date> getRecipientClass() {
        return Date.class;
    }
    
	@Override
	public ValidationResult validate(Date fieldValue) {
        int minAge, maxAge, age;
        
        minAge = Integer.parseInt(getAnnotation().param1());
        maxAge = Integer.parseInt(getAnnotation().param2());
        // Not strictly accurate, considering leap years, but it's for sanity checking
        age = (int)((System.currentTimeMillis() - fieldValue.getTime()) / 31556952000L);
        if (age < 0) {
            return ValidationResult.makeFailureWithMessageResult("The date of birth is in the future", MessageType.ERROR);
        } else if (age < minAge) {
            return ValidationResult.makeFailureWithMessageResult("Age of " + age + " is too young", MessageType.ERROR);
        } else if (age > maxAge) {
            return ValidationResult.makeFailureWithMessageResult("Age of " + age + " is too old", MessageType.ERROR);
        } else {
            return ValidationResult.makeSuccessResult();
        }
	}

}